package com.campus.counseling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.counseling.entity.Record;
import com.campus.counseling.model.mapper.RecordMapper;
import com.campus.counseling.model.dto.RecordDTO;
import com.campus.counseling.model.vo.ConsultationRecordVO;
import com.campus.counseling.service.RecordService;
import com.campus.counseling.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class RecordServiceImpl implements RecordService {

    private final RecordMapper recordMapper;

    @Override
    public Page<ConsultationRecordVO> getRecordList(Page<Record> page, RecordDTO query) {
        LambdaQueryWrapper<Record> wrapper = new LambdaQueryWrapper<>();
        String userRole = SecurityUtils.getUserRole();
        Long userId = SecurityUtils.getUserId();

        if ("student".equals(userRole)) {
            wrapper.eq(Record::getStudentId, userId);
        } else if ("counselor".equals(userRole)) {
            wrapper.eq(Record::getCounselorId, userId);
        }

        Page<Record> recordPage = recordMapper.selectPage(page, wrapper);
        Page<ConsultationRecordVO> voPage = new Page<>(page.getCurrent(), page.getSize(), recordPage.getTotal());
        voPage.setRecords(recordPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));
        return voPage;
    }

    @Override
    @Transactional
    public void createRecord(RecordDTO recordDTO) {
        Record record = new Record();
        BeanUtils.copyProperties(recordDTO, record);
        record.setCounselorId(SecurityUtils.getUserId());
        recordMapper.insert(record);
    }

    private ConsultationRecordVO convertToVO(Record record) {
        ConsultationRecordVO vo = new ConsultationRecordVO();
        BeanUtils.copyProperties(record, vo);
        return vo;
    }

    private boolean isAdmin() {
        String role = SecurityUtils.getUserRole();
        return "admin".equals(role) || "superadmin".equals(role);
    }
} 